package com.abu.auth.service;

import com.abu.auth.config.JwtProperties;
import com.abu.auth.mapper.MemberMapper;
import com.abu.auth.pojo.Member;
import com.abu.common.CookieUtils;
import com.abu.common.JwtUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.zhyd.oauth.model.AuthResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
@EnableConfigurationProperties(JwtProperties.class)
public class AuthService {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private MemberMapper memberMapper;

    public String checkLogin(AuthResponse response) {
        String responseStr = JSON.toJSON(response.getData()).toString();
        HashMap map = JSON.parseObject(responseStr, HashMap.class);

//        获取用户名
        String nickname = (String) map.get("nickname");
//        获取token对象
        String tokenObject = map.get("token").toString();
        HashMap hashMapToken = JSON.parseObject(tokenObject, HashMap.class);
//        获取openId
        String openId = hashMapToken.get("openId").toString();
        Member member = this.memberMapper.selectOne(new QueryWrapper<Member>().eq("openid", openId));
//        如果是第一次登陆则新增用户
        if (member == null) {
            member=new Member();
            member.setOpenid(openId);
            member.setNickname(nickname);
            member.setSex(StringUtils.equals(map.get("gender").toString(), "男") ? 2 : 1);
            this.memberMapper.insert(member);
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("nickname", nickname);
        hashMap.put("memberId", member.getId());
        String token = null;
        try {
            token = JwtUtils.generateToken(map,jwtProperties.getPrivateKey(), jwtProperties.getExpire() * 15);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }
}
